import { defineStore } from 'pinia'
import { userApi } from '../api/user.js'

export const useUserStore = defineStore('user', {
	state: () => ({
		userInfo: null,
		isLoggedIn: false
	}),

	actions: {
		async checkLogin() {
			try {
				const localUserInfo = uni.getStorageSync('userInfo')
				if (localUserInfo) {
					this.userInfo = JSON.parse(localUserInfo)
					this.isLoggedIn = true
					return true
				}
				return false
			} catch (error) {
				return false
			}
		},

		async login(e) {
			try {
				// 获取登录code
				const loginRes = await uni.login({
					provider: 'weixin'
				})

				console.log('获取登录code:', loginRes)

				// 调用后端登录接口，传入手机号的 code
				const result = await userApi.login({
					code: loginRes.code,
					phoneCode: e.detail.code // 添加手机号的 code
				})

				// 登录注册一体
				console.log('后端登录接口返回:', result)

				this.userInfo = result.data.userInfo
				this.isLoggedIn = true
				uni.setStorageSync('userInfo', JSON.stringify(result.data.userInfo))
			} catch (error) {
				console.error('登录失败:', error)
				uni.showToast({
					title: '登录失败',
					icon: 'none'
				})
				throw error
			}
		},

		async logout() {
			this.userInfo = null
			this.isLoggedIn = false
			uni.removeStorageSync('userInfo')
		},

		async loginWithPassword(data) {
			try {
				const result = await userApi.loginWithPassword(data)
				if (result.success) {
					this.userInfo = result.data.userInfo
					this.isLoggedIn = true
					uni.setStorageSync('token', result.data.token)
					uni.setStorageSync('userInfo', JSON.stringify(result.data.userInfo))
					return true
				}
				throw new Error(result.message)
			} catch (error) {
				console.error('密码登录失败:', error)
				uni.showToast({
					title: error.message || '登录失败',
					icon: 'none'
				})
				return false
			}
		},

		async register(form) {
			console.log('注册信息:', form)
			try {
				// 调用注册接口
				const result = await userApi.register(form)
				console.log('注册接口返回:', result)

				if (result.success) {
					// 保存用户信息到全局
					this.userInfo = result.data.userInfo
					this.isLoggedIn = true
					uni.setStorageSync('token', result.data.token)
					uni.setStorageSync('userInfo', JSON.stringify(result.data.userInfo))

					// 注册成功后跳转到首页
					uni.switchTab({
						url: '/pages/study/study'
					})
				} else {
					throw new Error(result.message || '注册失败')
				}
			} catch (error) {
				console.error('注册失败:', error)
				uni.showToast({
					title: error.message || '注册失败',
					icon: 'none'
				})
				throw error
			}
		},

		async uploadAvatar(form) {
			const result = await userApi.uploadAvatar(form)
			return result
		},

		// 更新用户资料
		async updateProfile(form) {
			// form的格式{avatar: '', username: '',openid: '' }
      const result = await userApi.updateProfile(form)
      // 更新用户信息
      console.log('更新用户信息:', result)
      this.userInfo = result.data.userInfo  
      uni.setStorageSync('userInfo', JSON.stringify(result.data.userInfo))
			return result
		}
	}
})
